﻿using supermarket.method;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Data.SqlClient;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace supermarket
{
    public partial class memberconsumption : Form
    {
        public SqlConnection sql = new Classgetsql().getcon();
        public memberconsumption ()
        {
            InitializeComponent();
        }

        private void btn_shop_Click ( object sender, EventArgs e )//消费
        {
            string phoneNumber = txtPhone1.Text.Trim();
            string pointsText = txtPoints1.Text.Trim();

            // 输入验证
            if (string.IsNullOrEmpty(phoneNumber))
            {
                MessageBox.Show("请输入手机号！");
                return;
            }

            if (!int.TryParse(pointsText, out int pointsToConsume) || pointsToConsume <= 0)
            {
                MessageBox.Show("请输入有效的消费积分（正整数）！");
                return;
            }

            // 执行消费
            ConsumePoints(phoneNumber, pointsToConsume);
            LoadData(dgv_user, "products");
        }

        private void ConsumePoints ( string phoneNumber, int pointsToConsume )
        {
            try
            {
                if (sql.State != ConnectionState.Open)
                {
                    sql.Open();
                }

                string shopCode = "SHP002";
                string shopName = "阳光便利店";

                string checkQuery = "SELECT id, name, integral FROM Table_user WHERE number = @PhoneNumber";
                using (SqlCommand checkCommand = new SqlCommand(checkQuery, sql))
                {
                    checkCommand.Parameters.AddWithValue("@PhoneNumber", phoneNumber);

                    using (SqlDataReader reader = checkCommand.ExecuteReader())
                    {
                        if (!reader.Read())
                        {
                            MessageBox.Show("未找到该手机号对应的用户。");
                            return;
                        }

                        int userId = reader.GetInt32(0);
                        string customerName = reader.GetString(1);
                        int currentPoints = reader.GetInt32(2);
                        reader.Close();

                        if (currentPoints < pointsToConsume)
                        {
                            MessageBox.Show($"积分不足！当前积分：{currentPoints}，需消费：{pointsToConsume}");
                            return;
                        }

                        using (SqlTransaction transaction = sql.BeginTransaction())
                        {
                            try
                            {
                                int newPoints = currentPoints - pointsToConsume;
                                string updateQuery = "UPDATE Table_user SET integral = @NewIntegral WHERE id = @UserId";
                                using (SqlCommand updateCommand = new SqlCommand(updateQuery, sql, transaction))
                                {
                                    updateCommand.Parameters.AddWithValue("@NewIntegral", newPoints);
                                    updateCommand.Parameters.AddWithValue("@UserId", userId);

                                    int rowsAffected = updateCommand.ExecuteNonQuery();

                                    if (rowsAffected == 0)
                                    {
                                        transaction.Rollback();
                                        MessageBox.Show("更新积分失败。");
                                        return;
                                    }
                                }

                                string insertSaleQuery = @"
                        INSERT INTO [super].[dbo].[SalesRecords] 
                            ([shop_code], [shop_name], [customer_name], [customer_phone], 
                             [sale_amount], [sale_date], [payment_method], [items_purchased])
                        VALUES 
                            (@ShopCode, @ShopName, @CustomerName, @CustomerPhone, 
                             @SaleAmount, GETDATE(), '积分支付', @ItemsPurchased)";

                                using (SqlCommand saleCommand = new SqlCommand(insertSaleQuery, sql, transaction))
                                {
                                    saleCommand.Parameters.AddWithValue("@ShopCode", shopCode);
                                    saleCommand.Parameters.AddWithValue("@ShopName", shopName);
                                    saleCommand.Parameters.AddWithValue("@CustomerName", customerName);
                                    saleCommand.Parameters.AddWithValue("@CustomerPhone", phoneNumber);
                                    saleCommand.Parameters.AddWithValue("@SaleAmount", pointsToConsume);
                                    saleCommand.Parameters.AddWithValue("@ItemsPurchased", $"积分消费 {pointsToConsume} 点");

                                    saleCommand.ExecuteNonQuery();
                                }

                                // 添加消费流水记录
                                string insertConsumptionQuery = @"
                                    INSERT INTO [dbo].[Consumption] 
                                        ([username], [phone], [ConsumptionType], [inegral], [inegralAll], [upload_time])
                                    VALUES 
                                        (@Username, @Phone, @ConsumptionType, @Integral, @IntegralAll, GETDATE())";

                                using (SqlCommand consumptionCommand = new SqlCommand(insertConsumptionQuery, sql, transaction))
                                {
                                    consumptionCommand.Parameters.AddWithValue("@Username", customerName);
                                    consumptionCommand.Parameters.AddWithValue("@Phone", phoneNumber);
                                    consumptionCommand.Parameters.AddWithValue("@ConsumptionType", "消费");
                                    consumptionCommand.Parameters.AddWithValue("@Integral", pointsToConsume);
                                    consumptionCommand.Parameters.AddWithValue("@IntegralAll", newPoints);

                                    consumptionCommand.ExecuteNonQuery();
                                }

                                transaction.Commit();
                                MessageBox.Show($"成功消费 {pointsToConsume} 积分。新余额：{newPoints}");
                                DisplayUserData(dgv_user);
                            }
                            catch (Exception ex)
                            {
                                transaction.Rollback();
                                MessageBox.Show($"操作失败，已回滚: {ex.Message}");
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show($"消费过程中发生错误：{ex.Message}");
            }
            finally
            {
                if (sql.State == ConnectionState.Open)
                {
                    sql.Close();
                }
            }
        }

        public void DisplayUserData ( DataGridView dgv_user )
        {
            try
            {
                if (sql.State != ConnectionState.Open)
                {
                    sql.Open();
                }

                string query = @"SELECT TOP 1000 [id], [name], [number], [class], [integral]
                        FROM [super].[dbo].[Table_user]";
                SqlDataAdapter adapter = new SqlDataAdapter(query, sql);
                DataTable dataTable = new DataTable();
                adapter.Fill(dataTable);
                dgv_user.DataSource = dataTable;
                dgv_user.Columns["id"].HeaderText = "ID";
                dgv_user.Columns["name"].HeaderText = "姓名";
                dgv_user.Columns["number"].HeaderText = "手机号";
                dgv_user.Columns["class"].HeaderText = "会员等级";
                dgv_user.Columns["integral"].HeaderText = "积分";

            }
            catch (Exception ex)
            {
                MessageBox.Show("错误: " + ex.Message, "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            finally
            {
                if (sql.State == ConnectionState.Open)
                {
                    sql.Close();
                }
            }
        }


        private void button3_Click ( object sender, EventArgs e )//
        {
            string phoneNumber = txtPhone.Text.Trim();
            string pointsText = txtPoints.Text.Trim();

            // 输入验证
            if (string.IsNullOrEmpty(phoneNumber))
            {
                MessageBox.Show("请输入手机号");
                return;
            }

            if (!int.TryParse(pointsText, out int pointsToAdd) || pointsToAdd <= 0)
            {
                MessageBox.Show("请输入有效的充值积分（正整数）！");
                return;
            }
            RechargePoints(phoneNumber, pointsToAdd);
            LoadData(dgv_user, "products");
        }

        private void panel2_Paint ( object sender, PaintEventArgs e )
        {
            LoadData(dgv_user, "products");
        }

        private void RechargePoints ( string phoneNumber, int pointsToAdd )
        {
            try
            {
                if (sql.State != ConnectionState.Open)
                {
                    sql.Open();
                }

                string checkQuery = "SELECT id, name, integral FROM Table_user WHERE number = @PhoneNumber";
                using (SqlCommand checkCommand = new SqlCommand(checkQuery, sql))
                {
                    checkCommand.Parameters.AddWithValue("@PhoneNumber", phoneNumber);

                    using (SqlDataReader reader = checkCommand.ExecuteReader())
                    {
                        if (!reader.Read())
                        {
                            MessageBox.Show("未找到该手机号对应的用户。");
                            return;
                        }

                        int userId = reader.GetInt32(0);
                        string userName = reader.GetString(1);
                        int currentPoints = reader.GetInt32(2);
                        reader.Close();

                        using (SqlTransaction transaction = sql.BeginTransaction())
                        {
                            try
                            {
                                int newPoints = currentPoints + pointsToAdd;
                                string updateQuery = "UPDATE Table_user SET integral = @NewIntegral WHERE id = @UserId";
                                using (SqlCommand updateCommand = new SqlCommand(updateQuery, sql, transaction))
                                {
                                    updateCommand.Parameters.AddWithValue("@NewIntegral", newPoints);
                                    updateCommand.Parameters.AddWithValue("@UserId", userId);

                                    int rowsAffected = updateCommand.ExecuteNonQuery();

                                    if (rowsAffected == 0)
                                    {
                                        transaction.Rollback();
                                        MessageBox.Show("更新积分失败。");
                                        return;
                                    }
                                }

                                // 添加充值流水记录
                                string insertConsumptionQuery = @"
                                    INSERT INTO [dbo].[Consumption] 
                                        ([username], [phone], [ConsumptionType], [inegral], [inegralAll], [upload_time])
                                    VALUES 
                                        (@Username, @Phone, @ConsumptionType, @Integral, @IntegralAll, GETDATE())";

                                using (SqlCommand consumptionCommand = new SqlCommand(insertConsumptionQuery, sql, transaction))
                                {
                                    consumptionCommand.Parameters.AddWithValue("@Username", userName);
                                    consumptionCommand.Parameters.AddWithValue("@Phone", phoneNumber);
                                    consumptionCommand.Parameters.AddWithValue("@ConsumptionType", "充值");
                                    consumptionCommand.Parameters.AddWithValue("@Integral", pointsToAdd);
                                    consumptionCommand.Parameters.AddWithValue("@IntegralAll", newPoints);

                                    consumptionCommand.ExecuteNonQuery();
                                }

                                transaction.Commit();
                                MessageBox.Show($"成功充值 {pointsToAdd} 积分。新余额：{newPoints}");
                                DisplayUserData(dgv_user);
                            }
                            catch (Exception ex)
                            {
                                transaction.Rollback();
                                MessageBox.Show($"操作失败，已回滚: {ex.Message}");
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show($"充值过程中发生错误：{ex.Message}");
            }
            finally
            {
                if (sql.State == ConnectionState.Open)
                {
                    sql.Close();
                }
            }
        }


        public void LoadData ( DataGridView dgv, string tableType )
        {
            try
            {
                if (sql.State != ConnectionState.Open)
                {
                    sql.Open();
                }

                string query;
                SqlDataAdapter adapter;
                DataTable dataTable = new DataTable();

                switch (tableType.ToLower())
                {
                   
                    case "products":
                        query = "select TOP 1000  username,phone,consumptionType,inegral,inegralAll,FORMAT(upload_time, 'yyyy-MM-dd HH:mm') AS upload_time from Consumption  order by id desc";
                        adapter = new SqlDataAdapter(query, sql);
                        adapter.Fill(dataTable);
                        dgv.DataSource = dataTable;
                        dgv.Columns["username"].HeaderText = "会员";
                        dgv.Columns["phone"].HeaderText = "手机号";
                        dgv.Columns["consumptionType"].HeaderText = "类型";
                        dgv.Columns["inegral"].HeaderText = "操作积分";
                        dgv.Columns["inegralAll"].HeaderText = "总积分";
                        dgv.Columns["upload_time"].HeaderText = "操作时间";
                        dgv.Columns["upload_time"].Width = 250;
                        dgv.Columns["phone"].Width = 200;
                        break;

                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("加载数据时发生错误: " + ex.Message, "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            finally
            {
                if (sql.State == ConnectionState.Open)
                {
                    sql.Close();
                }
            }
        }

    }
}
